import React from "react";
import { createStore, combineReducers, bindActionCreators } from "redux";
import { Provider, connect } from "react-redux";

import { counterPlusOne, counterMinusOne, counterReset } from "./actions";
import reducers from "./reducers";

// 创建store
const store = createStore(reducers);

class Counter extends React.Component {
  render() {
    const { count, counterPlusOne, counterMinusOne, counterReset } = this.props;
    return (
      <div>
        <h3>counter: plus/minus</h3>
        <hr />
        <div className="flex">
          <span className="icon" onClick={counterMinusOne}>
            {" "}
            -{" "}
          </span>
          <input className="input" value={count} />
          <span className="icon" onClick={counterPlusOne}>
            {" "}
            +{" "}
          </span>
        </div>
        <button className="danger_btn" onClick={counterReset}>
          RESET
        </button>
      </div>
    );
  }
}

// 向组件注入 属性
function mapStateToProps(state) {
  console.log('state:',state)
  return {
    count: state.count
  };
}

// 向组件注入 方法
function mapDispatchToProps(dispatch) {
  return bindActionCreators({ counterPlusOne, counterMinusOne, counterReset }, dispatch);
}

// 向counter组件注入灵魂 属性&方法
const ConnectedCounter = connect(
  mapStateToProps,
  mapDispatchToProps
)(Counter);

// 将功能组件包裹在注入了store的provider内
export class CounterApp extends React.Component {
  render() {
    return (
      <Provider store={store}>
        <ConnectedCounter />
      </Provider>
    );
  }
} 